package org.luxor.commons.websocket;

import org.luxor.commons.core.constant.BaseConst;
import org.luxor.commons.websocket.annotation.WebSocketServer;
import org.luxor.commons.websocket.exception.WsServerConnectInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;

/**
 * WebSocket 用户通知服务
 *
 * @author Mr.yan  @date 2021/8/6
 */
@Component
@WebSocketServer("/websocket/notices")
public class WsUserNoticeServer {
    private static final Logger log = LoggerFactory.getLogger(WsUserNoticeServer.class);

    public WsUserNoticeServer() {
        // An empty constructor
    }

    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(Session session) {
        Object token = session.getRequestParameterMap().get(BaseConst.TOKEN_NAME).get(0);
        if (token == null) {
            throw new WsServerConnectInvalidException("建立用户的WebSocket连接失败,身份凭证(token)找不到.");
        }
        log.info("【" + token + "】欢迎接入系统websocket通知通道.");
        WsSessionContextUtils.addSession(token.toString(), session);
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(Session session) {
        Object token = session.getRequestParameterMap().get(BaseConst.TOKEN_NAME).get(0);
        if (token != null) {
            WsSessionContextUtils.removeSession(token.toString());
        }
    }

    /**
     * 异常处理
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("与用户的WebSocket连接，出现网络异常", error);
    }

}